﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.Xml.Linq;
using RPGXEngine.World;

namespace RPGX.Graphics
{
    public class GraphicsSystem
    {
        #region Properties

        public GraphicsDeviceManager GDM
        {
            get { return this._gdm; }
            private set { this._gdm = value; }
        }
        private GraphicsDeviceManager _gdm = null;

        public Game Game
        {
            get { return this._game; }
            private set { this._game = value; }
        }
        private Game _game = null;

        public SpriteBatch SpriteBatch
        {
            get { return this._spriteBatch; }
            private set { this._spriteBatch = value; }
        }
        private SpriteBatch _spriteBatch = null;

        #endregion

        #region Public Methods

        public GraphicsSystem(Game game)
        {
            if (game == null)
                throw new ArgumentNullException("game");

            this.Game = game;

            this.GDM = new GraphicsDeviceManager(this.Game);
        }

        public void Render(GameTime time, HUD hud, GameWorld world)
        {
            this.Game.GraphicsDevice.Clear(ClearOptions.DepthBuffer | ClearOptions.Target, Color.CornflowerBlue, 1.0f, 0);

            Texture2D game = world.Render();

            this.SpriteBatch.Begin();

            if (game != null)
                this.SpriteBatch.Draw(game, this.Game.GraphicsDevice.Viewport.TitleSafeArea, Color.White);

            hud.Render(time, this.SpriteBatch);

            this.SpriteBatch.End();
        }

        public bool LoadContent(string settingsFileName)
        {
            GraphicsSettings settings = new GraphicsSettings();
            if (!settings.FromFile(settingsFileName))
                return false;

            this.LoadSettings(settings);

            this.SpriteBatch = new SpriteBatch(this.Game.GraphicsDevice);

            return true;
        }

        public void UnLoad()
        {
        }

        #endregion

        #region Private Methods

        private void LoadSettings(GraphicsSettings settings)
        {
            this.GDM.PreferredBackBufferWidth = settings.ScreenWidth;
            this.GDM.PreferredBackBufferHeight = settings.ScreenHeight;
            this.GDM.IsFullScreen = settings.FullScreen;

            this.GDM.ApplyChanges();
        }

        #endregion
    }
}
